
import logging

from models import UserInPlaylist,Song, SongInPlaylist, ActiveUser
from django.utils import simplejson as json

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.api import channel

def get_active_users():
    q=ActiveUser.all().fetch(100)
    return [ k.user for k in q ]

def get_song_key(lang):
    if lang=='e':
        parent='englishsong'
    else:
        parent='hindisong'
    return db.Key.from_path(parent, lang)


""" Song duplication is checked at client side only """
class Add(webapp.RequestHandler):
    def post(self):
        user=users.get_current_user()
        song=self.request.get('song')
        lang=self.request.get('lang')
        order=int(self.request.get('order'))
        if not song:
            logging.error('_song_ is missing in '+__file__)
            return

        u=UserInPlaylist(user=user, order=order)
        u.put()

        songkey=Song.all(keys_only=True).ancestor(get_song_key(lang)).filter('songname =', song).get()

        SongInPlaylist(parent=u, song_ref=songkey).put()
        self.response.out.write(song+' added to your playlist')

        jsonobj={'TYPE':'P',
                 'ACTOR':users.get_current_user().nickname(),
                 'ACTION':'ADD',
                 'SONG':song}
        messg=json.dumps(jsonobj)

        a_users=get_active_users()
        for u in a_users:
            if u==user:
                continue
            channel.send_message(u.user_id(), messg)

    def get(self):
        user=users.get_current_user()
        song=self.request.get('song')
        lang=self.request.get('lang')
        order=int(self.request.get('order'))
        if not song:
            logging.error('_song_ is missing in '+__file__)
            self.response.out.write('Song missing')
            return

        if not lang:
            logging.error('_lang_ is missing in '+__file__)
            self.response.out.write('Lang missing')
            return

        if not order:
            logging.error('_order_ missing in '+__file__)
            self.response.out.write('Order missing')
            return

        self.response.headers['Content-Type']='text/plain'
        uip=UserInPlaylist.all(keys_only=True)
        uip.filter('user =', user)
        u=uip.get()
        if u:
            self.response.out.write(user.nickname()+' already in playlist\n')
        else:
            u=UserInPlaylist()
            u.put()
            self.response.out.write(user.nickname()+' added to UserInPlaylist\n')

        pool=Song.all(keys_only=True)
        pool.ancestor(get_song_key(lang))
        pool.filter('songname =', song)
        songkey=pool.get()
        if not songkey:
            self.response.out.write('Song \''+song+'\' is not in datastore :(\n')
            return

        SongInPlaylist(parent=u, song_ref=songkey,order=order).put()
        self.response.out.write(song+' added to your playlist')

        jsonobj={'TYPE':'P',
                 'ACTOR':users.get_current_user().nickname(),
                 'ACTION':'ADD',
                 'SONG':song}
        messg=json.dumps(jsonobj)

        a_users=get_active_users()
        for u in a_users:
            if u==user:
                continue
            channel.send_message(u.user_id(), messg)
        

class Rem(webapp.RequestHandler):
    def get(self):
        user=users.get_current_user()
        song=self.request.get('song')
        if not song:
            logging.error('_song_ is missing in '+__file__)
            self.response.out.write('song_missing')
            return
        u_key=UserInPlaylist.all(keys_only=True).filter('user =', user).get()

        user_songs=SongInPlaylist.all().ancestor(u_key).fetch(100)
        for sng in user_songs:
            if sng.song_ref.songname==song:
                db.delete(sng.key())
                self.response.out.write('Song '+song+' has been deleted')
                break
        
        jsonobj={'TYPE':'P',
                 'ACTOR':user.nickname(),
                 'ACTION':'REM',
                 'SONG':song}
        messg=json.dumps(jsonobj)
        a_users=get_active_users()
        for u in a_users:
            if u==user:
                continue
            channel.send_message(u.user_id(), messg)


""" Vectors is a dictionary with mapping the following 
{ song : displacement, ... }
"""
class Reorder(webapp.RequestHandler):
    def get(self):
        user=users.get_current_user()
        vectors=self.request.get('vectors')
        if not vectors:
            loggin.error('Vector argument missing in '+__file__)
            self.response.out.write('vector_missing')
            
        reorders=json.loads(vectors)
        c=len(reorders)
        
        user_songs=SongInPlaylist.all()
        user_songs.ancestor(user)
        user_songs.order('order')
        us=user_songs.fetch(100)

        self.response.headers['Content-Type']='text/plain'
        self.response.out.write('Showing old playlist:\n')
        for s in us:
            self.response.out.write('\t'+s.song.songname+'\t'+s.order+'\n')
        
        for s in vectors.keys():
            dis=vectors[s]
            o_ord=us[s]
            n_odr=o_odr+dis
            if n_odr<o_odr:
                for i in range(n_odr, o_odr):
                    us[i].order=us[i].order+1
            else:
                for i in range(o_odr, n_idr):
                    us[i].order=us[i].order-1
            
            for s in us:
                s.put()
                
        self.response.out.write('Showing reordered playlist:\n')
        for s in us:
            self.response.out.write('\t'+s.song.songname+'\t'+s.order)
            
        
def main():
    app = webapp.WSGIApplication([('/pl/add', Add),
                                  ('/pl/rem', Rem),
                                  ('/pl/reorder', Reorder)], debug=True)
    run_wsgi_app(app)

if __name__=='__main__':
    main()
